package com.tc.config.auth.server.service.impl;

import com.tc.common.enums.UserStatus;
import com.tc.common.exception.BaseException;
import com.tc.common.utils.StringUtils;
import com.tc.config.auth.server.domain.LoginUser;
import com.tc.project.system.domain.SysUser;
import com.tc.project.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Auther: tianchao
 * @Date: 2020/5/16 19:45
 * @Description:
 */
@Service
@Slf4j
public class SpringDataUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 用户名登陆
     * @param username 登陆用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.selectUserByUsername(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }else if (UserStatus.DISABLE.getCode().equals(user.getStatus())){
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        return createLoginUser(user);
    }

    private UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user, null);
    }
}
